var _map;
var _tileLayer; //基础图层
var _heatLayer; //热力图图层
var _districtLayer; //行政区划图层
var _labelLayer; //标注符号化图层

var _baseLayerGroup;
var _districtLayerGorup;
var _heatMapGroup;
function initMap() {
  //初始化地图
  var crs = new L.Proj.CRS(
    "EPSG:900913",
    "+proj=merc +a=6378206 +b=6356584.314245179 +lat_ts=0.0 +lon_0=0.0 +x_0=0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs",
    {
      resolutions: (function () {
        level = 19;
        var res = [];
        res[0] = Math.pow(2, 18);
        for (var i = 1; i < level; i++) {
          res[i] = Math.pow(2, 18 - i);
        }
        return res;
      })(),
      origin: [0, 0],
      bounds: L.bounds([20037508.342789244, 0], [0, 20037508.342789244]),
    }
  );

  _map = L.map("map", {
    crs: crs,
    continuousWorld: true,
    worldCopyJump: false,
  }).setView([23.39552, 116.404], 4);

  // var tileLayer = new L.TileLayer.TileLoad('http://localhost:8080/_alllayers', {
  //     maxZoom: 9,
  //     minZoom: 4
  // });
  var url = "http://111.229.177.115:8080/maptile/{z}/{x}/{y}.jpg";
  //将图层加载到地图上，并设置最大的聚焦还有map样式
  _tileLayer = L.tileLayer(url, {
    maxZoom: 9,
    minZoom: 1,
    tms: true,
  });

  _tileLayer.addTo(_map);

  //创建行政区划数据
  var city_json = null;
  $.ajax({
    type: "GET",
    url: "../data/ningxia_city.json",
    async: false,
    dataType: "json",
  }).done(function (result) {
    city_json = result;
  });

  //加行政区划矢量图层
  _districtLayer = L.geoJson(city_json, {
    style: function (feature) {
      var style = business.getStyle(feature, _districtLayer);
      return style;
    },
    //添加事件（每个元素）
    onEachFeature: function (feature, layer) {
      business.onEachFeature_districtLayer(feature, layer);
    },
  });
  // _map.addLayer(_districtLayer);

  //创建标注图层
  var label_json = null;
  $.ajax({
    type: "GET",
    url: "../data/ningxia_city_center.json",
    async: false,
    dataType: "json",
  }).done(function (result) {
    label_json = result;
  });
  _labelLayer = L.geoJson(label_json, {
    //图标样式
    pointToLayer(feature, latlng) {
      var marker = business.createMarker(feature, latlng);
      return marker;
    },
  });
  // _map.addLayer(_labelLayer);

  ////创建热力图图层
  //构造带亮度值的经纬度数据（亮度值为1到1000随机数）
  _points_300 = _points_300.map(function (p) {
    return [p[0], p[1], getRandomIntInclusive(1, 1000)];
  });
  _heatLayer = L.heatLayer(_points_300, {
    //maxZoom: _map.getMaxZoom(),//一般不用设置，默认地图的最大zoomlevel(_map.getMaxZoom())
    blur: 11, //模糊化初始值，一般比半径大1/2
    gradient: {
      0.1: "blue",
      0.6: "cyan",
      0.7: "lime",
      0.8: "yellow",
      1: "red",
    }, //颜色变化范围，默认为{ .4: "blue", .6: "cyan", .7: "lime", .8: "yellow", 1: "red" }
    radius: 10, //点半径
  });

  //构建图层组
  _baseLayerGroup = L.layerGroup([_tileLayer]);
  _districtLayerGorup = L.layerGroup([_labelLayer, _districtLayer]);
  _heatMapGroup = L.layerGroup([_heatLayer]);
  //加载图层组
  _map.addLayer(_baseLayerGroup);
  // _map.addLayer(_districtLayerGorup);
  _map.addLayer(_heatMapGroup);
}

//热力图重载数据
function reloadHeatMap() {
  //构造带亮度值的经纬度数据（亮度值为1到1000随机数）
  var points_3001 = _points_300.map(function (p) {
    return [p[0], p[1], getRandomIntInclusive(1, 1000)];
  });
  //重载数据
  _heatLayer.setLatLngs(points_3001); //**此方法需要在图层已存在并加载后再执行 */
}

//添加移除图层
function showOrHideLayer() {
  _districtLayerGorup.hasLayer(_districtLayer)
    ? _districtLayerGorup.removeLayer(_districtLayer)
    : _districtLayerGorup.addLayer(_districtLayer); //添加移除单个图层
}

//添加移除图层组
function showOrHideLayerGroup() {
  _map.hasLayer(_districtLayerGorup)
    ? _map.removeLayer(_districtLayerGorup)
    : _map.addLayer(_districtLayerGorup); //添加移除整个图层组
}

//得到一个两数之间的随机整数，包括两个数在内
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值
}

//轮播展示图片
async function slideshowPNG() {
  var imageUrl = "",
    imageUrlTemplate = "../sources/radar/RADAR ({number}).png",
    imageBounds = [
      [37.013722391350385, 105.500956378170613],
      [37.461659050955568, 106.527558439070773],
    ];
  var image = L.imageOverlay(imageUrl, imageBounds).addTo(_map);
  for (let index = 1; index < 54; index++) {
    imageUrl = imageUrlTemplate.replace("{number}", index.toString());
    image.setUrl(imageUrl);

    //等一会
    await new Promise((resolve, reject) => {
      setTimeout(resolve, 500);
    });
  }
}
